package service;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import Utils.EnsureDataUtil;
import domain.User;
import repository.UserDao;

/**
 * Servlet implementation class DoLogin
 */
@WebServlet("/login.do")
public class UserService extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	public User verificationIdentity(String loginName,String pwd) {
		UserDao userDao = new UserDao();
	    return userDao.verificationIdentity(loginName, pwd);
	}
	
	public void rememberMe(HttpServletRequest request,HttpServletResponse response) {
		String loginName = request.getParameter("loginName");
		String pwd = request.getParameter("pwd");
		Cookie cookie = new Cookie("loginName",loginName);
		Cookie cookie1 = new Cookie("pwd",pwd);
		response.addCookie(cookie1);
		response.addCookie(cookie);
	}
	
	public String updatePwd(User user,String newPwd,String tryPwd) {
		String result = "FAIL";
		if(EnsureDataUtil.ensureNotEmptyData(newPwd, tryPwd) && newPwd.equals(tryPwd)) {
			UserDao userDao = new UserDao();
		    result = userDao.updateInfo(user, newPwd);
		}
		return result;
	}
	
	public String addUser(String userName,String pwd,String category,String belong_to) {
		String result = "FAIL";
		if(EnsureDataUtil.ensureNotEmptyData(userName, pwd) && EnsureDataUtil.ensureNotEmptyData(belong_to, category)) {
			UserDao userDao = new UserDao();
			List<User> list = new ArrayList<>();
			User user = new User();
			user.setUserName(userName);
			user.setPwd(pwd);
			user.setCategory(category);
			user.setBelongTo(belong_to);
			list.add(user);
		    result = userDao.insertUser(list);
		}
		return result;
	}
	
	public  List<User> queryAll() {
		UserDao userDao = new UserDao();
		return userDao.queryAll();
	}
	
	public boolean deleteUser(String nid) {
		int id = Integer.parseInt(nid);
		UserDao userDao = new UserDao();
		return userDao.deleteUser(id);
	}

}
